package com.beiing.tianshuai.tianshuai.mine.ui;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.PopupWindowSelectedAdapter;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.PopupWindowListBean;
import com.beiing.tianshuai.tianshuai.event.EventConstant;
import com.beiing.tianshuai.tianshuai.event.messages.OrderListEvent;
import com.beiing.tianshuai.tianshuai.mine.entity.MineOrderDataBean;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderDeleteBean;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderExtendTransportBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.OrderDataPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.OrderDataViewImpl;
import com.beiing.tianshuai.tianshuai.nim.session.SessionHelper;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.TimeUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.CustomEmptyLayout;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.beiing.tianshuai.tianshuai.widget.RoundAngleImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.tianshuai.easypopup.EasyPopup;

import java.text.MessageFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.beiing.tianshuai.tianshuai.app.HttpRequestConstant.USER_PIC_HEAD;

/**
 * 订单详情界面
 *
 * @author 赵皓
 */
public class OrderDetailActivity extends BaseActivity implements OrderDataViewImpl {

    /**
     * toolbar更多按钮
     */
    @BindView(R.id.toolbar_filter)
    ImageButton mToolbarFilter;

    /**
     * 订单状态提示文字
     */
    @BindView(R.id.tv_order_status)
    TextView mTvOrderStatus;

    /**
     * 订单详细信息提示文字
     */
    @BindView(R.id.tv_order_status_note)
    TextView mTvOrderStatusNote;

    /**
     * 收货人姓名
     */
    @BindView(R.id.tv_people)
    TextView mTvPeople;

    /**
     * 收货人手机
     */
    @BindView(R.id.tv_order_people_phone)
    TextView mTvOrderPeoplePhone;

    /**
     * 收货人地址信息
     */
    @BindView(R.id.ll_order_address)
    LinearLayout mLlOrderAddress;

    /**
     * 卖家姓名
     */
    @BindView(R.id.tv_seller_name)
    TextView mTvSellerName;

    /**
     * 卖家头像
     */
    @BindView(R.id.iv_seller_photo)
    ImageView mIvSellerPhoto;

    /**
     * 动态订单添加线性布局
     */
    @BindView(R.id.ll_order_item)
    LinearLayout mLlOrderItem;

    /**
     * 商品总额文字
     */
    @BindView(R.id.tv_order_all_price)
    TextView mTvOrderAllPrice;

    /**
     * 商品总额数字
     */
    @BindView(R.id.tv_order_all_price_number)
    TextView mTvOrderAllPriceNumber;

    /**
     * 运费文字
     */
    @BindView(R.id.tv_order_freight)
    TextView mTvOrderFreight;

    /**
     * 运费数字
     */
    @BindView(R.id.tv_order_freight_number)
    TextView mTvOrderFreightNumber;

    /**
     * 优惠文字
     */
    @BindView(R.id.tv_order_discount)
    TextView mTvOrderDiscount;

    /**
     * 优惠数字
     */
    @BindView(R.id.tv_order_discount_number)
    TextView mTvOrderDiscountNumber;

    /**
     * 支付文字
     */
    @BindView(R.id.tv_order_pay)
    TextView mTvOrderPay;

    /**
     * 支付数字
     */
    @BindView(R.id.tv_order_pay_number)
    TextView mTvOrderPayNumber;

    /**
     * 订单编号
     */
    @BindView(R.id.tv_order_id)
    TextView mTvOrderId;

    /**
     * 下单时间
     */
    @BindView(R.id.tv_order_time)
    TextView mTvOrderTime;

    /**
     * 付款时间
     */
    @BindView(R.id.tv_order_pay_time)
    TextView mTvOrderPayTime;

    /**
     * 支付方式
     */
    @BindView(R.id.tv_order_pay_way)
    TextView mTvOrderPayWay;

    /**
     * 配送方式
     */
    @BindView(R.id.tv_order_transport_way)
    TextView mTvOrderTransportWay;

    /**
     * 物流状态文字
     */
    @BindView(R.id.tv_order_transport)
    TextView mTvOrderTransport;

    /**
     * 物流时间
     */
    @BindView(R.id.tv_order_transport_time)
    TextView mTvOrderTransportTime;

    /**
     * 物流状态相对布局，判断是否显示
     */
    @BindView(R.id.rl_order_transport)
    RelativeLayout mRlOrderTransport;

    /**
     * 动态添加状态按钮
     */
    @BindView(R.id.ll_order_move_button)
    LinearLayout mLlOrderMoveButton;

    /**
     * 复制订单编号按钮
     */
    @BindView(R.id.tv_order_number_cope)
    TextView mTvOrderNumberCope;

    /**
     * 联系卖家
     */
    @BindView(R.id.tv_chat_seller)
    TextView mTvChatSeller;

    /**
     * 右上角蓝色背景中的状态图片
     */
    @BindView(R.id.iv_order_state)
    ImageView mIvOrderState;

    /**
     * 返回按钮
     */
    @BindView(R.id.toolbar_navigation)
    ImageButton mBack;

    /**
     * 加载过度视图
     */
    @BindView(R.id.cel_empty_view)
    CustomEmptyLayout mCustomEmptyLayout;

    /**
     * toolbar
     */
    @BindView(R.id.toolbar)
    Toolbar mToolbar;

    /**
     * 收货地址
     */
    @BindView(R.id.tv_address)
    TextView tvAddress;

    /**
     * 卖家布局
     */
    @BindView(R.id.rl_seller_name)
    RelativeLayout rlSellerName;

    /**
     * presenter
     */
    private OrderDataPresenter mPresenter;

    public static int time = 60 * 60 * 60;

    /**
     * popup 弹窗 取消订单
     */
    private EasyPopup mCancelOrderPopup;

    /**
     * 启动订单详情页
     *
     * @param context context
     * @param orderId 订单ID
     */
    public static void start(Context context, String orderId) {
        Intent intent = new Intent(context, OrderDetailActivity.class);
        intent.putExtra("orderId", orderId);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_data;
    }

    @Override
    protected void init() {
        // 设置通知栏
        QMUIStatusBarHelper.setStatusBarDarkMode(this);
        QMUIStatusBarHelper.translucent(this);
        mToolbar.setPadding(0, QMUIStatusBarHelper.getStatusbarHeight(mContext), 0, 0);

        initPresenter();
        initListener();
    }

    private void initListener() {
        // 返回
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //复制订单编号
        mTvOrderNumberCope.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", mTvOrderId.getText());
                // 将ClipData内容放到系统剪贴板里。
                if (cm != null) {
                    cm.setPrimaryClip(mClipData);
                    showShortText("订单编号已复制");
                }
            }
        });

        // 详细物流信息布局点击事件
        mRlOrderTransport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showShortText("查看详细物流信息");
            }
        });

        mToolbarFilter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showShortText("更多信息");
            }
        });
    }

    /**
     * 要请求的订单号
     */
    public void initPresenter() {
        mPresenter = new OrderDataPresenter(this);
        mPresenter.getOrderStatus(getOrdersId());
        //showShortText(getOrdersId());
    }

    /**
     * 网络请求开始展示
     */
    @Override
    public void showProgress() {
        if (mCustomEmptyLayout != null) {
            mCustomEmptyLayout.setInProgress();
        }
    }

    /**
     * 网络请求结束
     */
    @Override
    public void hideProgress() {
        if (mCustomEmptyLayout != null) {
            mCustomEmptyLayout.setChildrenVisible();
        }
    }

    /**
     * 网络请求成功，执行主要操作
     *
     * @param bean 订单详情数据
     */
    @Override
    public void onRequestSuccess(final MineOrderDataBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                //进入后，先清除按钮布局里的所有按钮
                mLlOrderMoveButton.removeAllViews();
                mLlOrderItem.removeAllViews();

                final MineOrderDataBean.DataBean data = bean.getData();
                Log.i(Integer.toString(code) + "各种数据" + data.getCompany(), data.getAid() + data.getAddress() + data.getId());
                Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.shape_bg_btn_radio_50);
                Drawable drawableBlue = ContextCompat.getDrawable(mContext, R.drawable.shape_bg_btn_radio_50_click);
                LogUtils.i("订单状态" + data.getIsStatus(), "orderStatus");
                switch (data.getIsStatus()) {
                    //存在此状态
                    case "0":
                        mTvOrderStatus.setText("等待付款");
                        CountDownTimer countDownTimer = new CountDownTimer(1800000, 1000) {
                            @Override
                            public void onTick(long l) {
                                long m = l / 1000 / 60;
                                long s = l / 1000 % 60;
                                mTvOrderStatusNote.setText(MessageFormat.format("还剩{0}分{1}秒", m, s));
                            }

                            @Override
                            public void onFinish() {
                                mTvOrderStatusNote.setText("已结束");
                            }
                        };
                        countDownTimer.start();
                        //取消订单
                        TextView mTvCancelOrder = getCancelOrder(drawable);
                        mLlOrderMoveButton.addView(mTvCancelOrder);
                        break;
                    case "1":
                        mTvOrderStatus.setText("支付成功");
                        mTvOrderStatusNote.setText("等待卖家发货");
                        //mIvOrderState.setImageDrawable(getResources().getDrawable(R.drawable.ic_logistics_middling_blue));
                        mIvOrderState.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_logistics_middling_blue));
//                      TextView mTvListenerCheckTransport1 = getCheckTransport(drawable);
//                      mLlOrderMoveButton.addView(mTvListenerCheckTransport1);              //查看物流

//                      TextView mTvListenerSureObtain1 = getSureObtain(drawableBlue);
//                      mTvListenerSureObtain1.setTextColor(Color.WHITE);                   //确认收货
//                      mLlOrderMoveButton.addView(mTvListenerSureObtain1);

                        //提醒发货按钮
                        TextView mTvRemindSend_out = getRemindSendOutButton(drawable);
                        mLlOrderMoveButton.addView(mTvRemindSend_out);
                        //联系客服,申请售后
                        TextView mTvRequestService1 = getRequestService(drawable, data);
                        mLlOrderMoveButton.addView(mTvRequestService1);
                        break;
                    //存在此状态
                    case "2":
                        mTvOrderStatus.setText("支付成功");
                        mTvOrderStatusNote.setText("物流正在配送中");
                        mIvOrderState.setImageDrawable(getResources().getDrawable(R.drawable.ic_logistics_middling_blue));

                        //显示物流信息
                        mRlOrderTransport.setVisibility(View.VISIBLE);
                        //物流详情信息 物流状态和时间
                        mTvOrderTransport.setText(bean.getData().getCompanylist());
                        mTvOrderTransportTime.setText(bean.getData().getCompanytime());
                        tvAddress.setText(bean.getData().getAddress());

                        //延长收货
                        TextView mTvExtendReceive = getExtendReceiveButton(drawable, data);
                        mLlOrderMoveButton.addView(mTvExtendReceive);

                        //查看物流
                        TextView mTvListenerCheckTransport = getCheckTransport(drawable);
                        mLlOrderMoveButton.addView(mTvListenerCheckTransport);
                        //确认收货  设置蓝色背景白色字
                        TextView mTvListenerSureObtain = getSureObtain(drawableBlue);
                        mTvListenerSureObtain.setTextColor(Color.WHITE);
                        mLlOrderMoveButton.addView(mTvListenerSureObtain);
                        break;
                    case "3":
                        mTvOrderStatus.setText("支付成功");
                        mTvOrderStatusNote.setText("交易已经完成，待评价");

                        //删除订单
                        TextView mTvDeleteOrder = getDeleterOrder(drawable, data);
                        mLlOrderMoveButton.addView(mTvDeleteOrder);
                        //添加评论按钮
                        TextView mTvComment_1 = getComment(drawable, data);
                        mLlOrderMoveButton.addView(mTvComment_1);
                        break;
                    case "4":
                        mTvOrderStatus.setText("交易成功");
                        mTvOrderStatusNote.setText("您的交易已经完成,已评价");
                        //追加评论按钮
                        TextView mTvAdditionalComment = getAdditionalCommentButton(drawable, data);
                        mLlOrderMoveButton.addView(mTvAdditionalComment);
                        //删除订单
                        TextView mTvDeleteOrder1 = getDeleterOrder(drawable, data);
                        mLlOrderMoveButton.addView(mTvDeleteOrder1);
                        break;
                    //存在此状态
                    case "5":
                        mTvOrderStatus.setText("售后中");
                        mTvOrderStatusNote.setText("您的退货申请正在受理");
//                        //联系客服
//                        TextView mTvRequestService = getRequestService(drawable, data);
//                        mLlOrderMoveButton.addView(mTvRequestService);
                        //查看进度
                        TextView mTvCancelAfterSale = getCancelAfterSale(drawable, data);
                        mLlOrderMoveButton.addView(mTvCancelAfterSale);

                        break;
                    case "6":
                        mTvOrderStatus.setText("退货成功");
                        mTvOrderStatusNote.setText("您的交易已经取消");

                        //删除订单
                        TextView mTvDeleteOrder2 = getDeleterOrder(drawable, data);
                        mLlOrderMoveButton.addView(mTvDeleteOrder2);
                        break;
                    case "7":
                        mTvOrderStatus.setText("支付成功");
                        mTvOrderStatusNote.setText("您的电子票已经使用");

                        //删除订单
                        TextView mTvDeleteOrder5 = getDeleterOrder(drawable, data);
                        mLlOrderMoveButton.addView(mTvDeleteOrder5);
                        //联系客服
                        TextView mTvRequestService2 = getRequestService(drawable, data);
                        mLlOrderMoveButton.addView(mTvRequestService2);
                        //添加评论
                        TextView mTvComment1 = getComment(drawable, data);
                        mLlOrderMoveButton.addView(mTvComment1);
                        break;
                    //暂时没有
                    case "8":
                        mTvOrderStatus.setText("退货失败");
                        mTvOrderStatusNote.setText("商家拒绝退货");

                        //删除订单
                        TextView mTvDeleteOrder3 = getDeleterOrder(drawable, data);
                        mLlOrderMoveButton.addView(mTvDeleteOrder3);
                        //联系客服,申请售后
                        TextView mTvRequestService3 = getRequestService(drawable, data);
                        mLlOrderMoveButton.addView(mTvRequestService3);
                        break;
                    case "9":
                        mTvOrderStatus.setText("交易成功");
                        mTvOrderStatusNote.setText("请在规定时间内使用电子票");

                        //联系客服,申请售后
                        TextView mTvRequestService4 = getRequestService(drawable, data);
                        mLlOrderMoveButton.addView(mTvRequestService4);
                        //查看电子票
                        TextView mTvInternetTicket = getInternetTicketButton(drawableBlue, data);
                        mTvInternetTicket.setTextColor(Color.WHITE);
                        mLlOrderMoveButton.addView(mTvInternetTicket);
                        break;
                    //不存在此状态
                    case "10":
                        mTvOrderStatus.setText("订单关闭");
                        mTvOrderStatusNote.setText("您支付超时");

                        TextView tvDeleteOrder2 = getDeleterOrder(drawable, data);
                        mLlOrderMoveButton.addView(tvDeleteOrder2);

                        TextView repayButton = getRepayButton(drawableBlue);
                        repayButton.setTextColor(Color.WHITE);
                        mLlOrderMoveButton.addView(repayButton);
                        break;
                    //存在此状态                                                        //存在此状态
                    case "11":
                        mTvOrderStatus.setText("订单关闭");
                        mTvOrderStatusNote.setText("不想要了");

                        TextView tvDeleteOrder = getDeleterOrder(drawable, data);
                        mLlOrderMoveButton.addView(tvDeleteOrder);
                        break;
                    default:
                        break;
                }
                break;
            case 401:
                showShortText("参数有误" + bean.getData().getId() + getOrdersId());
                break;
            default:
                showShortText("未知参数" + code);
                break;
        }
        //用户头像比例参数
        RequestOptions userPhotoOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .placeholder(R.drawable.default_avatar)
                .override(35, 35);
        //货物照片比例参数
        RequestOptions goodsPhotoOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .placeholder(R.drawable.img_loading_background)
                .override(445, 250);

        //收货人
        mTvPeople.setText(MessageFormat.format("收货人:{0}", bean.getData().getUname()));
        //收货人电话
        mTvOrderPeoplePhone.setText(bean.getData().getTel());
        //收货地址
        mTvOrderPayWay.setText(MessageFormat.format("收货地址:{0}", bean.getData().getAddress()));
        //发货人姓名********
        mTvSellerName.setText(bean.getData().getUsername());
        //发货人照片
        Glide.with(mContext.getApplicationContext())
                .load(USER_PIC_HEAD + bean.getData().getPhoto())
                .apply(userPhotoOptions)
                .into(mIvSellerPhoto);

        mTvOrderAllPriceNumber.setText(MessageFormat.format("¥{0}", bean.getData().getSmallPlan()));
        //订单总金额
        mTvOrderFreightNumber.setText(MessageFormat.format("¥{0}", bean.getData().getFreight()));
        //运费
        mTvOrderDiscountNumber.setText(MessageFormat.format("-¥{0}", bean.getData().getDiscount()));
        //优惠价格
        mTvOrderPayNumber.setText(MessageFormat.format("¥{0}", bean.getData().getAmountMoney()));
        //支付金额
        mTvOrderId.setText(MessageFormat.format("订单编号：{0}", bean.getData().getOrderNumber()));

        //支付方式
        mTvOrderPayWay.setText(MessageFormat.format("支付方式：{0}", bean.getData().getPayMethod()));

        //配送方式
        String transportWay = bean.getData().getCompany();
        if (TextUtils.isEmpty(transportWay)) {
            mTvOrderTransportWay.setVisibility(View.GONE);
        } else {
            mTvOrderTransportWay.setVisibility(View.VISIBLE);
            mTvOrderTransportWay.setText(MessageFormat.format("配送方式：{0}", transportWay));
        }

        if (bean.getData().getCreateTime() == null) {
            showShortText("下单时间为空");
            return;
        }
        try {
            String date = TimeUtils.longToString(
                    Long.valueOf(bean.getData().getCreateTime()) * 1000,
                    "yyyy-MM-dd HH:mm:ss"
            );
            //订单创建时间
            mTvOrderTime.setText(MessageFormat.format("下单时间：{0}", date));
        } catch (ParseException e) {
            mTvOrderTime.setText("下单时间：异常");
            e.printStackTrace();
        }
        if (bean.getData().getPaymentTime() == null) {
            showShortText("付款时间为空");
            return;
        }
        try {
            String date = TimeUtils.longToString(
                    Long.valueOf(bean.getData().getPaymentTime()) * 1000,
                    "yyyy-MM-dd HH:mm:ss"
            );//付款时间
            mTvOrderPayTime.setText(MessageFormat.format("付款时间：{0}", date));
        } catch (ParseException e) {
            mTvOrderPayTime.setText("付款时间：异常");
            e.printStackTrace();
        }

        //货单动态添加
        View reGoods = View.inflate(mContext, R.layout.item_order_goods, null);
        RoundAngleImageView mGoods = reGoods.findViewById(R.id.riv_order_photo);
        Glide.with(mContext.getApplicationContext())
                .load(HttpRequestConstant.ACTIVITY_PIC_HEAD + bean.getData().getCover())
                .apply(goodsPhotoOptions)
                .into(mGoods);

        TextView mTvGoodsTitle = reGoods.findViewById(R.id.tv_goods_name);
        //订单货物名字
        mTvGoodsTitle.setText(bean.getData().getAname());
        TextView mTvGoodsCreateTime = reGoods.findViewById(R.id.tv_goods_time);
        if (bean.getData().getActionTime() == null) {
            return;
        } else {
            try {
                String date = TimeUtils.longToString(
                        Long.valueOf(bean.getData().getActionTime()) * 1000, "MM.dd HH:mm");
                //货物时间
                mTvGoodsCreateTime.setText(MessageFormat.format("时间：{0}", date));
            } catch (ParseException e) {
                //货物时间
                mTvGoodsCreateTime.setText("时间：异常");
                e.printStackTrace();
            }
        }
        TextView mTvGoodsAddress = reGoods.findViewById(R.id.tv_goods_address);
        mTvGoodsAddress.setText(MessageFormat.format("地址:{0}", bean.getData().getActivity()));      //活动地址，发货地址
        TextView mTvGoodsKind = reGoods.findViewById(R.id.tv_goods_kind);
        mTvGoodsKind.setText(bean.getData().getTicketType());                                                 //货物种类
        TextView mTvGoodsNumber = reGoods.findViewById(R.id.tv_goods_number);
        mTvGoodsNumber.setText(MessageFormat.format("x{0}", bean.getData().getCount()));              //货物个数
        TextView mTvGoodsPrice = reGoods.findViewById(R.id.tv_goods_price);
        mTvGoodsPrice.setText(MessageFormat.format("¥{0}", bean.getData().getPrice()));
        //将动态布局加载到
        mLlOrderItem.addView(reGoods);
        CustomProgressDialog.stopLoading();

        // 获取卖家的用户id
        final String sellerUid = bean.getData().getUserId();
        // 联系卖家按钮点击事件
        mTvChatSeller.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SessionHelper.startP2PSession(mContext, sellerUid);
            }
        });
        // 卖家姓名信息点击事件
        rlSellerName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NewPersonalIndexActivity.start(mContext, sellerUid);
            }
        });
    }

    /**
     * 创建立即支付按钮
     *
     * @param drawable 按钮背景
     * @return 立即支付按钮
     */
    private TextView getPay(Drawable drawable) {
        View.OnClickListener onClickListenerPay = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShortText("立即支付");
            }
        };
        return createTextView("立即支付", onClickListenerPay, drawable);
    }

    /**
     * 创建添加评论按钮
     *
     * @param drawable 按钮背景
     * @return 添加评论按钮
     */
    private TextView getComment(Drawable drawable, final MineOrderDataBean.DataBean bean) {
        View.OnClickListener onClickListenerComment = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //showShortText("添加评论");
                OrderCommentActivity.start(mContext, bean.getAid(), bean.getUid(), bean.getId(),
                        bean.getCover(), bean.getPhoto(), bean.getRname(), "添加评价");
            }
        };
        return createTextView("添加评论", onClickListenerComment, drawable);
    }

    /**
     * 创建确认收货按钮
     *
     * @param drawable 按钮背景
     * @return 确认收货按钮
     */
    private TextView getSureObtain(Drawable drawable) {
        View.OnClickListener onClickListenerSureObtain = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShortText("确认收货");
            }
        };
        return createTextView("确认收货", onClickListenerSureObtain, drawable);
    }

    /**
     * 创建查看物流方法
     *
     * @param drawable 按钮背景
     * @return 查看物流按钮
     */
    private TextView getCheckTransport(Drawable drawable) {
        View.OnClickListener onClickListenerCheckTransport = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OrderTransportActivity.start(mContext, getOrdersId());
            }
        };
        return createTextView("查看物流", onClickListenerCheckTransport, drawable);
    }

    /**
     * 创建删除订单按钮
     *
     * @param drawable 按钮背景
     * @return 删除订单按钮
     */
    private TextView getDeleterOrder(Drawable drawable, final MineOrderDataBean.DataBean bean) {
        View.OnClickListener onClickListenerDeleteOrder = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                        "确认删除订单吗？", new CustomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            mPresenter.getOrderDelete(bean.getId());
                            dialog.dismiss();
                        } else {
                            dialog.dismiss();
                        }
                    }
                }).setNegativeButton("取消").setPositiveButton("确认").setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }
        };
        return createTextView("删除订单", onClickListenerDeleteOrder, drawable);
    }

    /**
     * 创建申请售后方法
     *
     * @param drawable 按钮背景
     * @return 申请售后按钮
     */
    private TextView getRequestService(Drawable drawable, final MineOrderDataBean.DataBean bean) {
        View.OnClickListener onClickListenerRequestService = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                OrderApplyAfterSaleActivity.start(mContext, bean.getId());

            }
        };
        return createTextView("申请售后", onClickListenerRequestService, drawable);
    }

    /**
     * 创建取消订单方法
     *
     * @param drawable 按钮背景
     * @return 取消订单按钮
     */
    private TextView getCancelOrder(Drawable drawable) {
        View.OnClickListener onClickListenerCancelOrder = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = "取消订单";
                String[] mCancelReason = {"不想要了", "拍多/拍错", "其他"};
                showCancelPopupWindow(mCancelReason, title);
            }
        };
        return createTextView("取消订单", onClickListenerCancelOrder, drawable);
    }

    /**
     * 创建重新支付按钮
     *
     * @param drawable 设置背景
     * @return 重新支付按钮
     */
    private TextView getRepayButton(Drawable drawable) {
        View.OnClickListener onClickListenerAgainPay = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShortText("重新支付");
            }
        };
        return createTextView("重新支付", onClickListenerAgainPay, drawable);
    }

    /**
     * 创建提醒发货按钮
     *
     * @param drawable 背景
     * @return 监听事件
     */
    private TextView getRemindSendOutButton(Drawable drawable) {
        View.OnClickListener onClickListenerAgainPay = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShortText("提醒发货");
            }
        };
        return createTextView("提醒发货", onClickListenerAgainPay, drawable);
    }

    /**
     * 创建延长收货按钮
     *
     * @param drawable 背景
     * @return 监听事件
     */
    private TextView getExtendReceiveButton(Drawable drawable, final MineOrderDataBean.DataBean bean) {
        View.OnClickListener onClickListenerAgainPay = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                        "只能申请一次延长收货\n确认继续申请吗？", new CustomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            //showShortText("订单号" + bean.getId());
                            mPresenter.getOrderExtentTransport(bean.getId());
                            dialog.dismiss();
                        } else {
                            dialog.dismiss();
                        }
                    }
                }).setNegativeButton("取消").setPositiveButton("确认").setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }
        };
        return createTextView("延长收货", onClickListenerAgainPay, drawable);
    }

    /**
     * 创建追加评论按钮
     *
     * @param drawable 背景
     * @return 监听事件
     */
    private TextView getAdditionalCommentButton(Drawable drawable, final MineOrderDataBean.DataBean bean) {
        View.OnClickListener onClickListenerAgainPay = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                OrderCommentActivity.start(mContext, bean.getAid(), bean.getUid(), bean.getId(),
                        bean.getCover(), bean.getPhoto(), bean.getRname(), "追加评价");
            }
        };
        return createTextView("追加评论", onClickListenerAgainPay, drawable);
    }

    /**
     * 创建电子票按钮lay
     *
     * @param drawable 背景
     * @return 监听事件
     */
    private TextView getInternetTicketButton(Drawable drawable, final MineOrderDataBean.DataBean bean) {
        View.OnClickListener onClickListenerAgainPay = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //showShortText("电子票会有的");
                Intent intent = new Intent(mContext, ETicketActivity.class);
                intent.putExtra("oid", bean.getId());
                startActivity(intent);
            }
        };
        return createTextView("电子票", onClickListenerAgainPay, drawable);
    }

    /**
     * 查看进度按钮
     *
     * @param drawable 背景
     * @return 监听事件
     */
    private TextView getCancelAfterSale(Drawable drawable, final MineOrderDataBean.DataBean bean) {
        View.OnClickListener onClickListenerCancelAfterSale = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将订单号传递过去
                OrderAfterSaleStateActivity.startActivityForResult(OrderDetailActivity.this, bean.getId());
            }
        };
        return createTextView("查看进度", onClickListenerCancelAfterSale, drawable);
    }

    /**
     * 封装动态创建按钮方法
     *
     * @param text            按钮文字
     * @param onClickListener 按钮点击事件
     * @param drawable        按钮背景
     * @return 返回text view
     */
    private TextView createTextView(String text, View.OnClickListener onClickListener, Drawable drawable) {
        TextView textView = new TextView(mContext);
        textView.setText(text);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
        //textView.setRight(10);      不可以直接这样写
        textView.setTextColor(ContextCompat.getColor(mContext, R.color.grey_333333));
        textView.setGravity(Gravity.CENTER);
        textView.setBackground(drawable);
        textView.setOnClickListener(onClickListener);
        LinearLayout.LayoutParams olp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        olp.setMargins(0, 0, DensityUtils.dp2px(mContext, 10), 0);
        textView.setLayoutParams(olp);
        return textView;
    }

    /**
     * 判断popup是否存在
     *
     * @param mList 传入列表选项
     * @param title 传入标题
     */
    private void showCancelPopupWindow(String[] mList, String title) {
        if (mCancelOrderPopup == null) {
            initGoodsStatePopupWindow(mList, title);
        }
        mCancelOrderPopup.showAtLocation(getCurrentFocus(), Gravity.BOTTOM, 0, 0);
    }

    /**
     * 创建popup
     *
     * @param mList 传入列表选项
     * @param title 传入标题
     */
    private void initGoodsStatePopupWindow(String[] mList, final String title) {
        //获取Activity根视图
        mCancelOrderPopup = new EasyPopup(this);
        RelativeLayout activityRootView = ((OrderApplyAfterSaleActivity) mContext).getRlRootView();
        mCancelOrderPopup.setContentView(R.layout.popwin_goods_state, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setAnimationStyle(R.style.AnimBottom)
                .setFocusAndOutsideEnable(true)
                .setBackgroundDimEnable(true)
                .setDimValue(0.4f)
                .setDimColor(Color.BLACK)
                .setDimView(activityRootView)
                .createPopup();
        //初始化视图
        View contentView = mCancelOrderPopup.getContentView();

        TextView tvTitle = contentView.findViewById(R.id.tv_popup_title);
        TextView tvPopupSure = contentView.findViewById(R.id.tv_popup_btn_bottom);
        ImageButton ibPopupClose = contentView.findViewById(R.id.ib_popup_close);
        RecyclerView rlPopupSelected = contentView.findViewById(R.id.rv_popup_list_selected);

        tvTitle.setText(title);

        //创建LinearLayoutManager 对象
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        //设置RecyclerView 布局
        rlPopupSelected.setLayoutManager(mLayoutManager);
        rlPopupSelected.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0),
                ContextCompat.getColor(mContext, R.color.white)));

        //创建适配器
        final PopupWindowSelectedAdapter adapter = new PopupWindowSelectedAdapter(mContext);
        //加载数据到适配器
        List<PopupWindowListBean> list = new ArrayList<>();
        for (String mRefundReason : mList) {
            PopupWindowListBean popupWindowListBean = new PopupWindowListBean();
            popupWindowListBean.setItemText(mRefundReason);
            popupWindowListBean.setSelected(false);
            list.add(popupWindowListBean);
        }
        adapter.appendData(list);
        rlPopupSelected.setAdapter(adapter);

        final EasyPopup finalPopup = mCancelOrderPopup;
        tvPopupSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<PopupWindowListBean> list = adapter.getList();
                for (PopupWindowListBean listBean : list) {
                    //如果数据被选中
                    if (listBean.isSelected()) {
                        showShortText("取消订单原因:" + listBean.getItemText());
                        //通过接口判断是否取消成功
                        finalPopup.dismiss();

                    }
                }
            }
        });
        ibPopupClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finalPopup.dismiss();
            }
        });
        adapter.setOnItemClickListener(new PopupWindowSelectedAdapter.OnItemClickListener() {
            @Override
            public void onItemSelected(int position, PopupWindowListBean bean) {
                List<PopupWindowListBean> list = adapter.getList();
                // 找到当前默认的选项，设置它的选择状态为false
                for (PopupWindowListBean listBean : list) {
                    if (listBean.isSelected()) {
                        listBean.setSelected(false);
                        break;
                    }
                }
                // 设置当前用户选择的item，设置他的选择状态为true
                list.get(position).setSelected(true);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private String getOrdersId() {
        Intent intent = getIntent();
        return intent.getStringExtra("orderId");
    }

    @Override
    public void onRequestFailed(Throwable throwable) {

    }

    /**
     * //监听回跳方法
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("调用了onActivityResult", "1234==========================");
        //showShortText("调用了onActivityResult");
        //请求码
        switch (requestCode) {
            //取消售后成功返回结果码
            case AppConstant.REQUEST_CODE_CANCEL_REFUND:
                //结果码
                switch (resultCode) {
                    case AppConstant.RESULT_CODE_CANCEL_REFUND:
                        //刷新数据
                        LogUtil.i("获取到了请求码" + AppConstant.RESULT_CODE_CANCEL_REFUND,
                                "取消售后成功1234");
                        if (mPresenter == null) {
                            mPresenter = new OrderDataPresenter(this);
                        }
                        mPresenter.getOrderStatus(getOrdersId());
                        break;
                    default:
                        break;
                }
                break;
            //申请退货成功返回结果码
            case AppConstant.REQUEST_CODE_APPLY_REFRESH:
                //结果码
                switch (resultCode) {
                    case AppConstant.RESULT_CODE_APPLY_TO_ORDER_DETAIL:
                        //刷新数据
                        LogUtil.i("获取到了请求码" + AppConstant.RESULT_CODE_APPLY_TO_ORDER_DETAIL,
                                "申请退货成功1234");
                        if (mPresenter == null) {
                            mPresenter = new OrderDataPresenter(this);
                        }
                        mPresenter.getOrderStatus(getOrdersId());
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void extentOrderSuccess(OrderExtendTransportBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                showShortText("延长收货成功");
                break;
            case 201:
                showShortText("已经延长过了哦\n不能再次延长");
                break;
            case 202:
                showShortText("延长失败");
                break;
            case 401:
                showShortText("参数有误");
                break;
            default:
                showShortText("未知错误");
                break;
        }
    }

    @Override
    public void extentOrderError(Throwable throwable) {
        showShortText("延长收货网络请求失败" + throwable);
        LogUtil.e("=========", "出错" + throwable.getMessage());
    }

    @Override
    public void delOrderSuccess(OrderDeleteBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                //返回刷新
                showShortText("删除订单成功");
                //删除订单成功发送消息通知消息列表页更新
                RxBus.getInstanceBus().post(
                        new OrderListEvent<>(
                                EventConstant.EVENT_TYPE_UPDATE_ORDER_LIST,
                                "删除订单成功")
                );
                finish();
                break;
            case 202:
                showShortText("删除失败");
                break;
            case 401:
                showShortText("参数有误");
                break;
            default:
                showShortText("未知参数");
                LogUtil.e("未知参数", "未知参数" + code);
                break;
        }
    }

    @Override
    public void delOrderError(Throwable throwable) {
        showShortText("网络请求失败");
        LogUtils.e(throwable.getMessage(), "delOrderError");
    }


}
